import React, { useState, useEffect } from 'react';
import { 
  Input, 
  Button, 
  Table, 
  Space, 
  message,
  Card,
  Row,
  Col,
  Modal,
  Select,
  Form
} from 'antd';
import { 
  SearchOutlined, 
  SettingOutlined,
  TrophyOutlined,
  MoreOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getProxyConfigList, getProxyList, updateProxyConfig } from '../../api/shop';

const { Option } = Select;

// 代理商数据类型
interface AgentType {
  id: number;
  user_id: number;
  store_id: number;
  level: number;
  proxy_store_id: number;
  username: string;
  nickname: string;
  phone: string;
  avatar: string;
  created_at: string;
  updated_at: string;
}

// 分页数据类型
interface PaginationType {
  current_page: number;
  page_size: number;
  total: number;
  total_pages: number;
  has_prev: boolean;
  has_next: boolean;
  prev_page: number;
  next_page: number;
}

// 代理规则类型
interface AgentRule {
  level: string;
  salesVolume: number;
  salesAmount: number;
  agentPrice: number;
}

// 代理配置类型
interface ProxyConfig {
  id: number;
  store_id: number;
  level: number;
  amount: number;
  sales: number;
  commission_rate: number;
  created_at: string;
  updated_at: string;
}

const Agent: React.FC = () => {
  const [searchText, setSearchText] = useState('');
  const [loading, setLoading] = useState(false);
  const [isSettingsModalVisible, setIsSettingsModalVisible] = useState(false);
  const [proxyConfigList, setProxyConfigList] = useState<ProxyConfig[]>([]);
  const [agentList, setAgentList] = useState<AgentType[]>([]);
  const [pagination, setPagination] = useState<PaginationType>({
    current_page: 1,
    page_size: 10,
    total: 0,
    total_pages: 0,
    has_prev: false,
    has_next: false,
    prev_page: 0,
    next_page: 0
  });
  const [agentRules, setAgentRules] = useState<AgentRule[]>([
    { level: '银牌', salesVolume: 0, salesAmount: 0, agentPrice: 0 },
    { level: '金牌', salesVolume: 0, salesAmount: 0, agentPrice: 0 }
  ]);
  const [form] = Form.useForm();

  // 获取代理配置列表
  const fetchProxyConfigList = async () => {
    try {
      setLoading(true);
      const response = await getProxyConfigList();
      console.log('代理配置列表响应:', response);
      setProxyConfigList(response.list || []);
    } catch (error) {
      console.error('获取代理配置列表失败:', error);
      message.error('获取代理配置列表失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 获取代理商列表
  const fetchAgentList = async (page: number = 1, keyword: string = '') => {
    try {
      setLoading(true);
      const response = await getProxyList({
        page,
        page_size: pagination.page_size,
        keyword: keyword || undefined
      });
      console.log('代理商列表响应:', response);
      setAgentList(response.list || []);
      setPagination(response.pagination || pagination);
    } catch (error) {
      console.error('获取代理商列表失败:', error);
      message.error('获取代理商列表失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取代理商列表
  useEffect(() => {
    fetchAgentList();
  }, []);


  // 处理代理设置
  const handleAgentSettings = async () => {
    setIsSettingsModalVisible(true);
    // 打开模态框时获取代理配置列表
    await fetchProxyConfigList();
  };

  // 确认代理设置
  const handleConfirmSettings = async (values: any) => {
    setLoading(true);
    try {
      // 构建配置数据
      const configs = values.rules?.map((rule: any) => ({
        level: rule.level === '银牌' ? 1 : rule.level === '金牌' ? 2 : 3,
        amount: Number(rule.salesAmount) * 100, // 转换为分，确保是数字
        sales: Number(rule.salesVolume), // 确保是数字
        commission_rate: Number(rule.agentPrice) / 100 // 转换为小数，确保是数字
      })) || [];

      console.log('更新代理配置:', configs);
      const response = await updateProxyConfig({ configs });
      console.log('更新代理配置响应:', response);
      
      message.success('代理设置保存成功！');
      setIsSettingsModalVisible(false);
      
      // 刷新代理配置列表
      await fetchProxyConfigList();
    } catch (error) {
      console.error('保存代理配置失败:', error);
      message.error('保存失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 添加代理规则
  const handleAddRule = () => {
    setAgentRules([...agentRules, { level: '钻石', salesVolume: 0, salesAmount: 0, agentPrice: 0 }]);
  };

  // 删除代理规则
  const handleDeleteRule = (index: number) => {
    if (agentRules.length > 1) {
      const newRules = agentRules.filter((_, i) => i !== index);
      setAgentRules(newRules);
    } else {
      message.warning('至少需要保留一条规则');
    }
  };

  // 表格列配置
  const columns: ColumnsType<AgentType> = [
    {
      title: '代理人',
      dataIndex: 'nickname',
      key: 'nickname',
      width: 120,
      render: (nickname: string, record: AgentType) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <img 
            src={record.avatar} 
            alt={nickname}
            style={{ width: '32px', height: '32px', borderRadius: '50%' }}
            onError={(e) => {
              // 使用data URL避免网络请求
              e.currentTarget.src = '';
              e.currentTarget.onerror = null; // 防止再次触发错误
            }}
          />
          <span>{nickname}</span>
        </div>
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '代理等级',
      dataIndex: 'level',
      key: 'level',
      width: 120,
      render: (level: number) => {
        const levelConfig = {
          1: { text: '银牌', color: 'default', icon: <TrophyOutlined style={{ color: '#C0C0C0' }} /> },
          2: { text: '金牌', color: 'gold', icon: <TrophyOutlined style={{ color: '#FFD700' }} /> },
          3: { text: '钻石', color: 'purple', icon: <TrophyOutlined style={{ color: '#9C27B0' }} /> }
        };
        const config = levelConfig[level as keyof typeof levelConfig];
        return (
          <Space>
            {config.icon}
            <span>{config.text}</span>
          </Space>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (created_at: string) => {
        const date = new Date(created_at);
        return date.toLocaleString('zh-CN');
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: () => (
        <div 
          style={{ 
            cursor: 'pointer', 
            color: '#1890ff',
            display: 'flex',
            alignItems: 'center',
            gap: '8px'
          }}
          onClick={() => setIsSettingsModalVisible(true)}
        >
          <MoreOutlined />
          <span>代理设置</span>
        </div>
      ),
    },
  ];

  // 处理搜索
  const handleSearch = () => {
    fetchAgentList(1, searchText);
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize?: number) => {
    if (pageSize) {
      setPagination(prev => ({ ...prev, page_size: pageSize }));
    }
    fetchAgentList(page, searchText);
  };

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card style={{ borderRadius: '8px' }}>
        {/* 顶部搜索和按钮区域 */}
        <Row justify="space-between" align="middle" style={{ marginBottom: '16px' }}>
          <Col>
            <Space>
              <span style={{ fontSize: '16px', fontWeight: 'bold' }}>代理商</span>
              <Input
                placeholder="搜索代理商"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onPressEnter={handleSearch}
                style={{ width: 300 }}
                allowClear
              />
              <Button 
                type="primary" 
                icon={<SearchOutlined />}
                onClick={handleSearch}
                style={{ borderRadius: '6px' }}
              >
                搜索
              </Button>
            </Space>
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<SettingOutlined />}
              onClick={handleAgentSettings}
              style={{ borderRadius: '6px' }}
            >
              代理设置
            </Button>
          </Col>
        </Row>

        {/* 表格区域 */}
        <Table
          columns={columns}
          dataSource={agentList}
          loading={loading}
          pagination={{
            current: pagination.current_page,
            total: pagination.total,
            pageSize: pagination.page_size,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: handlePageChange,
            onShowSizeChange: handlePageChange,
          }}
          scroll={{ x: 1200 }}
          rowKey="id"
        />
      </Card>

      {/* 代理设置弹窗 */}
      <Modal
        title="代理设置"
        open={isSettingsModalVisible}
        onCancel={() => setIsSettingsModalVisible(false)}
        footer={null}
        width={800}
        style={{ top: 20 }}
      >
        <div style={{ padding: '20px 0' }}>
          <div style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '20px' }}>代理配置列表</div>
          
          {/* 显示代理配置数据 */}
          {proxyConfigList.length > 0 && (
            <div style={{ marginBottom: '20px' }}>
              <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>当前配置：</div>
              {proxyConfigList.map((config) => (
                <div key={config.id} style={{ 
                  padding: '12px', 
                  border: '1px solid #e8e8e8', 
                  borderRadius: '6px', 
                  marginBottom: '8px',
                  backgroundColor: '#fafafa'
                }}>
                  <Row>
                    <Col span={6}>
                      <div style={{ fontSize: '14px', color: '#666' }}>等级</div>
                      <div style={{ fontSize: '16px', fontWeight: 'bold' }}>
                        {config.level === 1 ? '银牌' : 
                         config.level === 2 ? '金牌' : 
                         config.level === 3 ? '钻石' : 
                         `L${config.level}`}
                      </div>
                    </Col>
                    <Col span={6}>
                      <div style={{ fontSize: '14px', color: '#666' }}>金额要求</div>
                      <div style={{ fontSize: '16px', fontWeight: 'bold', color: '#ff4d4f' }}>
                        ¥{(config.amount / 100).toFixed(2)}
                      </div>
                    </Col>
                    <Col span={6}>
                      <div style={{ fontSize: '14px', color: '#666' }}>销售要求</div>
                      <div style={{ fontSize: '16px', fontWeight: 'bold' }}>{config.sales}件</div>
                    </Col>
                    <Col span={6}>
                      <div style={{ fontSize: '14px', color: '#666' }}>佣金比例</div>
                      <div style={{ fontSize: '16px', fontWeight: 'bold', color: '#52c41a' }}>
                        {(config.commission_rate * 100).toFixed(1)}%
                      </div>
                    </Col>
                  </Row>
                </div>
              ))}
            </div>
          )}
          
          <div style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '20px' }}>达成规则</div>
          
          <Form
            form={form}
            onFinish={handleConfirmSettings}
            layout="vertical"
          >
                         {/* 表头 */}
             <Row style={{ 
               backgroundColor: '#f5f5f5', 
               padding: '12px 16px',
               borderRadius: '6px',
               marginBottom: '16px',
               fontWeight: 'bold'
             }}>
               <Col span={5} style={{ color: '#333' }}>代理等级</Col>
               <Col span={5} style={{ color: '#333' }}>销售量(&gt;)</Col>
               <Col span={1} style={{ color: '#333' }}></Col>
               <Col span={5} style={{ color: '#333' }}>销售金额(&gt;)</Col>
               <Col span={5} style={{ color: '#333' }}>代理价(%)</Col>
               <Col span={3} style={{ color: '#333' }}>操作</Col>
             </Row>

                         {/* 规则行 */}
             {agentRules.map((rule, index) => (
               <Row key={index} style={{ marginBottom: '16px', alignItems: 'center' }}>
                 <Col span={5}>
                   <Form.Item
                     name={['rules', index, 'level']}
                     initialValue={rule.level}
                     style={{ marginBottom: 0 }}
                   >
                     <Select style={{ width: '100%' }}>
                       <Option value="银牌">银牌</Option>
                       <Option value="金牌">金牌</Option>
                       <Option value="钻石">钻石</Option>
                     </Select>
                   </Form.Item>
                 </Col>
                 <Col span={5}>
                   <Form.Item
                     name={['rules', index, 'salesVolume']}
                     initialValue={rule.salesVolume}
                     style={{ marginBottom: 0 }}
                   >
                     <Input placeholder="销售量" type="number" />
                   </Form.Item>
                 </Col>
                 <Col span={1} style={{ textAlign: 'center', color: '#1890ff', fontWeight: 'bold' }}>
                   &amp;
                 </Col>
                 <Col span={5}>
                   <Form.Item
                     name={['rules', index, 'salesAmount']}
                     initialValue={rule.salesAmount}
                     style={{ marginBottom: 0 }}
                   >
                     <Input placeholder="销售金额" type="number" />
                   </Form.Item>
                 </Col>
                 <Col span={5}>
                   <Form.Item
                     name={['rules', index, 'agentPrice']}
                     initialValue={rule.agentPrice}
                     style={{ marginBottom: 0 }}
                   >
                     <Input placeholder="代理价" type="number" suffix="%" />
                   </Form.Item>
                 </Col>
                 <Col span={3} style={{ textAlign: 'center' }}>
                   <Button
                     type="text"
                     danger
                     onClick={() => handleDeleteRule(index)}
                     style={{ fontSize: '14px' }}
                   >
                     删除
                   </Button>
                 </Col>
               </Row>
             ))}

                         {/* 添加规则按钮 */}
             <div style={{ textAlign: 'center', marginBottom: '20px' }}>
               <Button
                 type="dashed"
                 onClick={handleAddRule}
                 style={{ 
                   width: '100%',
                   height: '40px',
                   borderRadius: '6px',
                   border: '2px dashed #d9d9d9'
                 }}
               >
                 添加规则
               </Button>
             </div>

            {/* 确认按钮 */}
            <div style={{ textAlign: 'center' }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                style={{ 
                  width: '120px', 
                  height: '40px',
                  borderRadius: '6px'
                }}
              >
                确认
              </Button>
            </div>
          </Form>
        </div>
      </Modal>
    </div>
  );
};

export default Agent; 